/*
package com.android.baseconfig.data.http.okhttp.interceptor;

import android.text.TextUtils;

import com.android.baseconfig.constact.AppConstant;
import com.android.baseconfig.constact.ComParamContact;
import com.android.baseconfig.constact.ECode;
import com.android.baseconfig.data.http.okhttp.OkHttpManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.het.basic.base.RxBus;
import com.het.basic.data.api.token.HetParamsMerge;
import com.het.basic.data.api.token.TokenManager;
import com.het.basic.data.api.token.model.AuthModel;
import com.het.basic.data.api.utils.Api;
import com.het.basic.model.ApiResult;
import com.het.basic.utils.DateTimeUtils;
import com.het.log.Logc;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;

*/
/**
 * -----------------------------------------------------------------
 * Copyright © 2016年 clife. All rights reserved.
 * Shenzhen H&T Intelligent Control Co.,Ltd.
 * -----------------------------------------------------------------
 * File: HeTInterceptor.java
 * Create: 2016/6/22 15:18
 * Author: uuxia
 * 网络数据拦截器，主要拦截数据过滤出Token类错误信息做全局事件分发
 **//*

public class HeTInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private int errorCount = 0;
    private static long refreshTokenTime = 0L;

    public static void main(String[] ar) {
        String param = "accessToken=108a059386f64b6597f41e4b1e6573e2&appId=30048&deviceTypeId=8&timestamp=1467801957925";
        //getGetRequestParams(param);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = process(chain);
        return response;
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType == null)
            return false;
        if (mediaType.type() != null && mediaType.type().equals("text")) {
//            Logc.i("uuok.file.type:" + mediaType.type());
            return true;
        }
        if (mediaType.subtype() != null) {
//            Logc.i("uuok.file.subtype:" + mediaType.subtype());
            if (mediaType.subtype().equals("json")) {
                return true;
            }
        }
        return false;
    }

    private Response processResponse(Chain chain, Request request, Response response) throws IOException {
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        String bodyString = buffer.clone().readString(charset);
        //Logc.i("uuok network interceptor:" + bodyString + " host:" + request.url().toString() + "\r\n header:" + request.headers());
        boolean isText = isText(contentType);
        if (!TextUtils.isEmpty(bodyString)) {
            Logc.e("uuok", HeTLoggerInterceptor.print(bodyString, response.request()));
        }
        if (!isText) {
            return response;
        }
        if (errorCount > 5) {
            errorCount = 0;
            return response;
        }

        if (!TextUtils.isEmpty(bodyString)) {
            ApiResult apiResult = new Gson().fromJson(bodyString, ApiResult.class);
            if (apiResult != null) {
                AuthModel authModel;
                switch (apiResult.getCode()) {
                    case ComParamContact.Code.ACCESS_TOKEN_EXPIRED: //AccessToken错误或已过期
                        errorCount++;
                        Logc.i(HeTLoggerInterceptor.print(bodyString, response.request()));
                        authModel = refreshToken();
                        if (authModel != null) {
                            return processAccessTokenError(chain, request);
                        }
                        break;
//                    case ComParamContact.Code.NO_ACCESS_TOKEN://缺少授权信息,没有accessToken,应该是没有登录
                    case ComParamContact.Code.REFRESH_TOKEN_EXPIRED://RefreshToken错误或已过期
                        */
/*authModel = reLogin();
                        if (authModel != null) {
                            return processRefreshTokenError(chain, request);
                        }*//*

                        errorCount++;
                        Logc.i(HeTLoggerInterceptor.print(bodyString, response.request()));
                        notifyLoginExit(apiResult);
                        break;
                    case ComParamContact.Code.OTHER_PHONE_LOGINED://帐号在其它手机已登录
                        */
/*authModel = reLogin();
                        if (authModel != null) {
                            return processAccessTokenError(chain, request);
                        }*//*

                        errorCount++;
                        notifyLoginExit(apiResult);
                        break;
                    case ComParamContact.Code.ERROR_SIGN://签名错误
                        errorCount++;
                        Logc.i(HeTLoggerInterceptor.print(bodyString, response.request()));
                        return processSignError(chain, request);
                    case ComParamContact.Code.TIMESTAMP_ERROR://timestamp过期
                        errorCount++;
                        Logc.i(HeTLoggerInterceptor.print(bodyString, response.request()));
                        Type type = new TypeToken<ApiResult<Long>>() {
                        }.getType();
                        ApiResult<Long> aaa = new Gson().fromJson(bodyString, type);
                        //Logc.e("uuok.timestapm:" + aaa.getData(), false);
                        TokenManager.getInstance().setTimestamp(aaa.getData());
//                        TokenManager.getInstance().setTimestamp((long) 111);
//                        return response;//processTimestampError(chain, request);
                        return processTimestampError(chain, request);
                    default:
                        break;
                }
            }
        }
        errorCount = 0;
        return response;
    }

    private Response process(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response response = chain.proceed(request);
//        Object obj = request.tag();
//        Logc.i("uuok....process...."+obj);
        */
/**通过如下的办法曲线取到请求完成的数据
         *
         * 原本想通过  originalResponse.body().string()
         * 去取到请求完成的数据,但是一直报错,不知道是okhttp的bug还是操作不当
         *
         * 然后去看了okhttp的源码,找到了这个曲线方法,取到请求完成的数据后,根据特定的判断条件去判断token过期
         *//*

        return processResponse(chain, request, response);
        */
/*ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        String bodyString = buffer.clone().readString(charset);
        //Logc.i("uuok network interceptor:" + bodyString + " host:" + request.url().toString() + "\r\n header:" + request.headers());
        boolean isText = isText(contentType);
        if (!isText) {
            return response;
        }

        if (!TextUtils.isEmpty(bodyString)) {
            ApiResult apiResult = new Gson().fromJson(bodyString, ApiResult.class);
            if (apiResult != null) {
                AuthModel authModel;
                switch (apiResult.getCode()) {
                    case ComParamContact.Code.ACCESS_TOKEN_EXPIRED: //AccessToken错误或已过期
                        Logc.i(HeTLoggerInterceptor.print(bodyString, request));
                        authModel = refreshToken();
                        if (authModel != null) {
                            return processAccessTokenError(chain, request);
                        }
                        break;
//                    case ComParamContact.Code.NO_ACCESS_TOKEN://缺少授权信息,没有accessToken,应该是没有登录
                    case ComParamContact.Code.REFRESH_TOKEN_EXPIRED://RefreshToken错误或已过期
                        *//*
*/
/*authModel = reLogin();
                        if (authModel != null) {
                            return processRefreshTokenError(chain, request);
                        }*//*
*/
/*
                        Logc.i(HeTLoggerInterceptor.print(bodyString, request));
                        notifyLoginExit(apiResult.getMsg());
                        break;
                    case ComParamContact.Code.OTHER_PHONE_LOGINED://帐号在其它手机已登录
                        *//*
*/
/*authModel = reLogin();
                        if (authModel != null) {
                            return processAccessTokenError(chain, request);
                        }*//*
*/
/*
                        notifyLoginExit(apiResult.getMsg());
                        break;
                    case ComParamContact.Code.ERROR_SIGN://签名错误
                        Logc.i(HeTLoggerInterceptor.print(bodyString, request));
                        return processSignError(chain, request);
                    case ComParamContact.Code.TIMESTAMP_ERROR://timestamp过期
                        Logc.i(HeTLoggerInterceptor.print(bodyString, request));
                        Type type = new TypeToken<ApiResult<Long>>() {
                        }.getType();
                        ApiResult<Long> aaa = new Gson().fromJson(bodyString, type);
                        //Logc.e("uuok.timestapm:" + aaa.getData(), false);
                        TokenManager.getInstance().setTimestamp(aaa.getData());
//                        TokenManager.getInstance().setTimestamp((long) 111);
                        return processTimestampError(chain, request);
                    default:
                        break;
                }
            }
        }

//        response.body().close();
//        return chain.proceed(request);
        return response;*//*

    }

    */
/**
     * 处理签名
     *
     * @param body
     * @param path
     * @return
     *//*

    private String processSign(FormBody body, String path, boolean https) {
        HetParamsMerge het = new HetParamsMerge();
        het.setPath(path);
        het.isHttps(https);
        boolean isSign = false;
        for (int i = 0; i < body.size(); i++) {
            String name = body.encodedName(i);
            String value = body.encodedValue(i);
            try {
                value = URLDecoder.decode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (name.equals(ComParamContact.Common.SIGN)) {
                isSign = true;
                continue;
            }
            if (name.equals(ComParamContact.Common.ACCESSTOKEN)) {
                value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                //Logc.i("uuok.ACCESSTOKEN:" + value);
            } else if (name.equals(ComParamContact.Common.REFRESH_TOKEN)) {
                value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getRefreshToken();
                //Logc.i("uuok.REFRESH_TOKEN:" + value);
            } else if (name != null && name.equals(ComParamContact.Common.TIMESTAMP)) {
                value = String.valueOf(TokenManager.getInstance().getTimestamp());
                //Logc.i("uuok.TIMESTAMP:" + value);
            }
            het.add(name, value);
        }
        if (isSign) {
            return het.sign();
        }
        return null;
    }

    */
/**
     * 处理签名错误
     *
     * @param chain
     * @param request
     * @return
     * @throws IOException
     *//*

    private Response processSignError(Chain chain, Request request) throws IOException {
        String method = request.method();
        // create a new request and modify it accordingly using the new token
        FormBody oldBody = (FormBody) request.body();
        if (oldBody == null) {
            if (request.method().equalsIgnoreCase("GET")) {
                oldBody = getRequestParams(request.url().query());
            } else {
                return chain.proceed(request);
            }
        }
        String path = request.url().pathSegments().get(0);
        boolean ishttps = request.url().url().toString().startsWith("https");
        String sign = processSign(oldBody, path, ishttps);
        //Logc.i("uuok.sign2:" + sign);
        FormBody.Builder newBody = new FormBody.Builder();
        for (int i = 0; i < oldBody.size(); i++) {
            String name = oldBody.encodedName(i);
            String value = oldBody.encodedValue(i);
            if (!TextUtils.isEmpty(name)) {
                if (name.equals(ComParamContact.Common.SIGN)) {
                    if (!TextUtils.isEmpty(sign)) {
                        value = sign;
                    }
                }
            }
            newBody.addEncoded(name, value);
        }

        Request newRequest;
        if (method.equalsIgnoreCase("GET")) {
            String url = packageParams(newBody.build());
            //Logc.i("uuok.GET.Error.newUrl:" + url);
            HttpUrl newHrrpIrl = request.url().newBuilder().query(url).build();
            newRequest = request.newBuilder().url(newHrrpIrl).get().build();
        } else {
            String url = packageParams(newBody.build());
            //Logc.i("uuok.GET.Error.newUrl:" + url);
            newRequest = request.newBuilder().post(newBody.build()).build();
        }
//        return chain.proceed(newRequest);
        Response response = chain.proceed(newRequest);
        return processResponse(chain, newRequest, response);
    }

    */
/**
     * 处理刷新Token错误
     *
     * @param chain
     * @param request
     * @return
     * @throws IOException
     *//*

    private Response processRefreshTokenError(Chain chain, Request request) throws IOException {
        return processError(chain, request, ComParamContact.Common.REFRESH_TOKEN, TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getRefreshToken());
    }

    */
/**
     * 处理AccessToke错误
     *
     * @param chain
     * @param request
     * @return
     * @throws IOException
     *//*

    private Response processAccessTokenError(Chain chain, Request request) throws IOException {
        return processError(chain, request, ComParamContact.Common.ACCESSTOKEN, TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken());
    }

    */
/**
     * 处理时间戳过期错误
     *
     * @param chain
     * @param request
     * @return
     * @throws IOException
     *//*

    private Response processTimestampError(Chain chain, Request request) throws IOException {
        return processError(chain, request, ComParamContact.Common.TIMESTAMP, TokenManager.getInstance().getTimestamp() + "");
    }

    */
/**
     * 处理HeT网络请求出现的业务错误
     *
     * @param chain
     * @param request
     * @param key
     * @param data
     * @return
     * @throws IOException
     *//*

    private Response processError(Chain chain, Request request, String key, String data) throws IOException {
        // create a new request and modify it accordingly using the new token
        String method = request.method();
        RequestBody body = request.body();
        if (body instanceof FormBody) {
            FormBody oldBody = (FormBody) request.body();
            if (oldBody == null) {
                if (method.equalsIgnoreCase("GET")) {
                    oldBody = getRequestParams(request.url().query());
                } else {
                    return chain.proceed(request);
                }
            }

            FormBody.Builder newBody = new FormBody.Builder();
            for (int i = 0; i < oldBody.size(); i++) {
                String name = oldBody.encodedName(i);
                String value = oldBody.encodedValue(i);
                if (!TextUtils.isEmpty(name)) {
                    if (name.equals(key)) {
                        value = data;
                    }
                    if (name.equals(ComParamContact.Common.SIGN)) {
                        String path = request.url().pathSegments().get(0);
                        boolean ishttps = request.url().url().toString().startsWith("https");
                        if (path == null || path.equalsIgnoreCase("v1")) {
                            try {
                                path = URLDecoder.decode(request.url().encodedPath(), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        String ret = processSign(oldBody, path, ishttps);
                        Logc.i("uuok.sign1.path:" + path + " sign:" + ret + " pathSegments:" + request.url().pathSegments().toString() + " url:" + request.url() + " encodedPath:" + request.url().encodedPath());
                        if (!TextUtils.isEmpty(ret)) {
                            value = ret;
                        }
                    } else if (name.equals(ComParamContact.Common.TIMESTAMP)) {
                        value = String.valueOf(TokenManager.getInstance().getTimestamp());
                    } else if (name.equals(ComParamContact.Common.ACCESSTOKEN)) {
                        value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                    }
                }
//            newBody.add(name, value);
                try {
                    value = URLDecoder.decode(value, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                newBody.addEncoded(name, value);
            }

            Request newRequest;
            if (method.equalsIgnoreCase("GET")) {
                String url = packageParams(newBody.build());
                //Logc.i("uuok.GET.Error.newUrl:" + url);
                HttpUrl newHrrpIrl = request.url().newBuilder().query(url).build();
                newRequest = request.newBuilder().url(newHrrpIrl).get().build();
            } else {
                String url = packageParams(newBody.build());
                try {
                    url = URLDecoder.decode(url, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //Logc.i("uuok.post.Error.newUrl:" + url);
                newRequest = request.newBuilder().post(newBody.build()).build();
            }
            // retry the request
//        originalResponse.body().close();
            Response response = chain.proceed(newRequest);
            return processResponse(chain, newRequest, response);
//        return chain.proceed(newRequest);
        } else if (body instanceof MultipartBody) {
            final String appId = "form-data; name=\"appId\"";
            final String accessToken = "form-data; name=\"accessToken\"";
            final String timestamp = "form-data; name=\"timestamp\"";
            MultipartBody multipartBody = (MultipartBody) request.body();
            MultipartBody.Builder newMulBuilder = new MultipartBody.Builder();
            for (int i = 0; i < multipartBody.size(); i++) {
                MultipartBody.Part part = multipartBody.part(i);
                Class pCls = (Class) part.getClass();
                Field[] fs = pCls.getDeclaredFields();
                Headers headers = null;
                RequestBody rBody = null;
                for (int j = 0; j < fs.length; j++) {
                    Field f = fs[j];
                    f.setAccessible(true); //设置些属性是可以访问的
                    Object val = null;//得到此属性的值
                    try {
                        val = f.get(part);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    if (val instanceof Headers) {
                        headers = (Headers) val;
                    } else if (val instanceof RequestBody) {
                        rBody = (RequestBody) val;
                    }
                }
                if (headers != null) {
                    String name = headers.value(0);
                    if (TextUtils.isEmpty(name))
                        continue;
                    if (name.equalsIgnoreCase(appId)) {
                        newMulBuilder.addPart(MultipartBody.Part.createFormData(ComParamContact.Common.APPID, AppConstant.APPID));
                    } else if (name.equalsIgnoreCase(accessToken)) {
                        String acccess = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                        newMulBuilder.addPart(MultipartBody.Part.createFormData(ComParamContact.Common.ACCESSTOKEN, acccess));
                    } else if (name.equalsIgnoreCase(timestamp)) {
                        newMulBuilder.addPart(MultipartBody.Part.createFormData(ComParamContact.Common.TIMESTAMP, String.valueOf(TokenManager.getInstance().getTimestamp())));
                    } else {
                        newMulBuilder.addPart(part);
                    }
                }
            }
            Request newRequest = request.newBuilder().post(newMulBuilder.build()).build();
            Response response = chain.proceed(newRequest);
            return processResponse(chain, newRequest, response);
        } else {
            FormBody oldBody = (FormBody) request.body();
            if (oldBody == null) {
                if (method.equalsIgnoreCase("GET")) {
                    oldBody = getRequestParams(request.url().query());
                } else {
                    return chain.proceed(request);
                }
            }
            FormBody.Builder newBody = new FormBody.Builder();
            for (int i = 0; i < oldBody.size(); i++) {
                String name = oldBody.encodedName(i);
                String value = oldBody.encodedValue(i);
                if (!TextUtils.isEmpty(name)) {
                    if (name.equals(key)) {
                        value = data;
                    }
                    if (name.equals(ComParamContact.Common.SIGN)) {
                        String path = request.url().pathSegments().get(0);
                        boolean ishttps = request.url().url().toString().startsWith("https");
                        String ret = processSign(oldBody, path, ishttps);
                        //Logc.i("uuok.sign1:" + ret);
                        if (!TextUtils.isEmpty(ret)) {
                            value = ret;
                        }
                    } else if (name.equals(ComParamContact.Common.TIMESTAMP)) {
                        value = String.valueOf(TokenManager.getInstance().getTimestamp());
                    } else if (name.equals(ComParamContact.Common.ACCESSTOKEN)) {
                        value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                    }
                }
//            newBody.add(name, value);
                try {
                    value = URLDecoder.decode(value, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                newBody.addEncoded(name, value);
            }

            Request newRequest;
            if (method.equalsIgnoreCase("GET")) {
                String url = packageParams(newBody.build());
                //Logc.i("uuok.GET.Error.newUrl:" + url);
                HttpUrl newHrrpIrl = request.url().newBuilder().query(url).build();
                newRequest = request.newBuilder().url(newHrrpIrl).get().build();
            } else {
                String url = packageParams(newBody.build());
                try {
                    url = URLDecoder.decode(url, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //Logc.i("uuok.post.Error.newUrl:" + url);
                newRequest = request.newBuilder().post(newBody.build()).build();
            }
            // retry the request
//        originalResponse.body().close();
            Response response = chain.proceed(newRequest);
            return processResponse(chain, newRequest, response);
        }
    }

    private Response processErrorBak(Chain chain, Request request, String key, String data) throws IOException {
        // create a new request and modify it accordingly using the new token
        String method = request.method();
        FormBody oldBody = (FormBody) request.body();
        if (oldBody == null) {
            if (method.equalsIgnoreCase("GET")) {
                oldBody = getRequestParams(request.url().query());
            } else {
                return chain.proceed(request);
            }
        }
        FormBody.Builder newBody = new FormBody.Builder();
        for (int i = 0; i < oldBody.size(); i++) {
            String name = oldBody.encodedName(i);
            String value = oldBody.encodedValue(i);
            if (!TextUtils.isEmpty(name)) {
                if (name.equals(key)) {
                    value = data;
                }
                if (name.equals(ComParamContact.Common.SIGN)) {
                    String path = request.url().pathSegments().get(0);
                    boolean ishttps = request.url().url().toString().startsWith("https");
                    String ret = processSign(oldBody, path, ishttps);
                    //Logc.i("uuok.sign1:" + ret);
                    if (!TextUtils.isEmpty(ret)) {
                        value = ret;
                    }
                }
            }
//            newBody.add(name, value);
            try {
                value = URLDecoder.decode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            newBody.addEncoded(name, value);
        }

        Request newRequest;
        if (method.equalsIgnoreCase("GET")) {
            String url = packageParams(newBody.build());
            //Logc.i("uuok.GET.Error.newUrl:" + url);
            HttpUrl newHrrpIrl = request.url().newBuilder().query(url).build();
            newRequest = request.newBuilder().url(newHrrpIrl).get().build();
        } else {
            String url = packageParams(newBody.build());
            try {
                url = URLDecoder.decode(url, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //Logc.i("uuok.post.Error.newUrl:" + url);
            newRequest = request.newBuilder().post(newBody.build()).build();
        }
        // retry the request
//        originalResponse.body().close();
        Response response = chain.proceed(newRequest);
        return processResponse(chain, newRequest, response);
//        return chain.proceed(newRequest);
    }

    */
/**
     * 处理Token
     *
     * @param chain
     * @param request
     * @return
     * @throws IOException
     *//*

    private Response processHetException(Chain chain, Request request) throws IOException {
        // create a new request and modify it accordingly using the new token
        FormBody oldBody = (FormBody) request.body();
        FormBody.Builder newBody = new FormBody.Builder();
        for (int i = 0; i < oldBody.size(); i++) {
            String name = oldBody.encodedName(i);
            String value = oldBody.encodedValue(i);
            if (!TextUtils.isEmpty(name)) {
                if (name.equals(ComParamContact.Common.ACCESSTOKEN)) {
                    value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                } else if (name.equals(ComParamContact.Common.REFRESH_TOKEN)) {
                    value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getRefreshToken();
                } else if (name != null && name.equals(ComParamContact.Common.TIMESTAMP)) {
//                    value = String.valueOf(System.currentTimeMillis());
                    value = String.valueOf(TokenManager.getInstance().getTimestamp());
                }
            }
            try {
                value = URLDecoder.decode(value, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            newBody.addEncoded(name, value);
        }

        Request newRequest = request.newBuilder().post(newBody.build()).build();
        // retry the request
//        originalResponse.body().close();
//        return chain.proceed(newRequest);
        Response response = chain.proceed(newRequest);
        return processResponse(chain, newRequest, response);
    }

    */
/**
     * 同步请求重新登录
     *
     * @return
     * @throws IOException
     *//*

    private AuthModel reLogin() throws IOException {
        //从ACache缓存中去出用户名和密码
        */
/*LoginInfo loginInfo = LoginCache.getInstance().get();
        if (loginInfo == null)
            return null;
        //同步方法请求登录方法
        Call<ApiResult<AuthModel>> call = Api.getInstance().reLogin(loginInfo.getUsername(), loginInfo.getPassword());
        ApiResult<AuthModel> newToken = call.execute().body();
        if (newToken != null) {
            int code = newToken.getCode();
            if (code == ComParamContact.Code.HTTP_SUCESS) {
                if (newToken.getData() != null) {
                    TokenManager.getInstance().setAuthModel(newToken.getData());
                    return newToken.getData();
                }
            } else {
                //如果刷新都失败了,那只能通知上层退出登陆了
                notifyLoginExit(newToken);
            }
        }*//*

        return null;
    }

    */
/**
     * 同步请求刷新Token
     *
     * @return
     * @throws IOException
     *//*

    private synchronized AuthModel refreshToken() throws IOException {
        long timestamp = System.currentTimeMillis();
        long cal = timestamp - refreshTokenTime;
//        Logc.e("uu @#@#@#@#@#@#@#@# " + cal + " " + refreshTokenTime);
        //如果两次小于10s
        if (cal < 10) {
            return TokenManager.getInstance().getAuthModel();
        }
        //同步方法刷新Token
        Call<ApiResult<AuthModel>> call = Api.getInstance().refreshTokenSync();
        ApiResult<AuthModel> newToken = call.execute().body();
        if (newToken != null) {
            int code = newToken.getCode();
            if (code == ComParamContact.Code.HTTP_SUCESS) {
                if (newToken.getData() != null) {
                    refreshTokenTime = System.currentTimeMillis();
                    TokenManager.getInstance().setAuthModel(newToken.getData());
                    return newToken.getData();
                }
            } else {
                //如果刷新都失败了,那只能通知上层登陆推出了
                notifyLoginExit(newToken);
            }
        }
        return null;
    }

    private void notifyLoginExit(ApiResult apiResult) {
        //如果刷新都失败了,那只能通知上层登录退出了
//        RxManage.getInstance().post(ECode.Token.EC_LOGINOUT, msg);
        String msg = DateTimeUtils.utc2BeiJingTime(apiResult.getMsg());
        Logc.e("notifyLoginExit ################## " + msg, false);
        RxBus.getInstance().post(ECode.Token.EC_LOGINOUT, msg);
        //业务出错,可以把所有HTTP请求干掉.
        OkHttpManager.getClient().dispatcher().cancelAll();
        TokenManager.getInstance().clearAuth();
    }

    */
/**
     * 将GET请求的参数封装成FormBody
     *
     * @param params
     * @return
     *//*

    private FormBody getRequestParams(String params) {
        if (params == null)
            return null;
        String[] strArr = params.split("&");
        if (strArr == null) {
            return null;
        }

        TreeMap<String, String> map = new TreeMap<>();
        FormBody.Builder fBulder = new FormBody.Builder();
        for (String s : strArr) {
            String[] sArr = s.split("=");
            if (sArr.length < 2)
                continue;
            if (sArr[0] != null && sArr[0].equals(ComParamContact.Common.TIMESTAMP)) {
                sArr[1] = String.valueOf(TokenManager.getInstance().getTimestamp());
            } else if (sArr[0] != null && sArr[0].equals(ComParamContact.Common.ACCESSTOKEN)) {
                sArr[1] = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
            }
            map.put(sArr[0], sArr[1]);
            fBulder.addEncoded(sArr[0], sArr[1]);
        }
        FormBody formBody = fBulder.build();
        return formBody;
    }

    */
/**
     * 封装参数
     *
     * @param oldBody
     * @return
     *//*

    private String packageParams(FormBody oldBody) {
        List<String> namesAndValues = new ArrayList<>();
        for (int i = 0; i < oldBody.size(); i++) {
            String name = oldBody.encodedName(i);
            String value = oldBody.encodedValue(i);
            if (!TextUtils.isEmpty(name)) {
                namesAndValues.add(name);
                if (name.equals(ComParamContact.Common.TIMESTAMP)) {
                    value = String.valueOf(TokenManager.getInstance().getTimestamp());
                } else if (name.equals(ComParamContact.Common.ACCESSTOKEN)) {
                    value = TokenManager.getInstance().getAuthModel() == null ? "" : TokenManager.getInstance().getAuthModel().getAccessToken();
                }
                try {
                    value = URLDecoder.decode(value, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                namesAndValues.add(value);
            }
        }
        StringBuilder sb = new StringBuilder();
        namesAndValuesToQueryString(sb, namesAndValues);
        return sb.toString();
    }

    */
/**
     * 合并GET参数
     *
     * @param out
     * @param namesAndValues
     *//*

    private void namesAndValuesToQueryString(StringBuilder out, List<String> namesAndValues) {
        for (int i = 0, size = namesAndValues.size(); i < size; i += 2) {
            String name = namesAndValues.get(i);
            String value = namesAndValues.get(i + 1);
            if (i > 0) out.append('&');
            out.append(name);
            if (value != null) {
                out.append('=');
                out.append(value);
            }
        }
    }
}
*/
